//
// User Controller
//
var ObjectID   = require('mongoose').Types.ObjectId;
var fs         = require('fs');

// gm:         GraphicsMagick node module.
// dependency: You need to apt-get install GraphicsMagick first then
//             npm install gm
// to use:     var gm = require('gm');
var gm         = require('gm');



module.exports = function(app, passport) {

   // Login
   app.route('/users/login')
      .get(function(req, res) {
         res.render('users/login', { message: req.flash('loginMessage'), /*csrf: req.csrfToken()*/ });
      })
      .post(passport.authenticate('my-local-login', {
         //successRedirect    : '/home', 
         failureRedirect      : '/users/login',   
         failureFlash         : true // allow flash messages
      }), function(req, res, next){
         if(!req.body.rememberme) {
            res.clearCookie('_rme');
            return next();
         }
         var token = req.user.generateHash(req.user._id + Date.now());
         Domain.User.update({_id: req.user._id}, {rememberme: token}, function(err, num){
            if(err) return next();
            res.cookie('_rme', token, {path: '/', httpOnly: true, maxAge: 1000 * 60 * 60 * 24 * 7}) ;   // 7 days remember me cookie
            return next();
         });
      }, function(req, res){
         var returnUrl = req.flash('returnUrl');
         if(returnUrl == undefined || returnUrl == null || returnUrl.length == 0)
            res.redirect(301, '/home');
         else
            res.redirect(301, returnUrl);
      });

   // Signup
   app.route('/users/signup')
      .get(function(req, res) {
         res.render('users/signup', { message: req.flash('signupMessage'), /*csrf: req.csrfToken()*/ });
      })
      .post(passport.authenticate('my-local-signup', {
         successRedirect      : '/home', 
         failureRedirect      : '/users/signup', 
         failureFlash         : true // allow flash messages
      }));

   // Logout
   app.route('/users/logout')
      .get(function(req, res) {
         res.clearCookie('_rme');
         req.logout();
         res.redirect('/home');
      });

   // List Users
   app.route('/users/list')
      .get(function(req, res){
         Domain.User.find({}).populate('joinedclubs').populate('club').populate('userdetail').exec(function(err, users){
            if(err) throw err;
            res.render('users/list', {user: req.user, users: users});
         });
      });

   // User Detail
   app.route('/users/profile/:id')
      .get(function(req, res) {
         var id = req.params.id;
         Domain.User.findById(id).populate('club').exec(function(err, doc){
            if(err)  
               res.send(404, 'could not find the user');
            else{
               Domain.UserDetail.findOne({uid: doc._id}, function(err, ud){
                  res.render('users/profile', {profile: doc, profile_detail: ud, user: req.user, csrf: req.csrfToken() });
               });
            }
         });
      })

      .post(app.isLoggedIn, function(req, res){
         var id = req.params.id;
         if(req.user._id.toString() != id) res.redirect('back');
         if(!req.files.myFile) res.redirect('back');

         // Only authenticated user can change his self photo.
         Domain.UserDetail.findOne({ uid: req.user._id}, function(err, doc){
            if(err) throw err;
            fs.readFile(req.files.myFile.path, function (err, data) {
               if(doc == null) {
                  doc = new Domain.UserDetail();
                  doc.uid = req.user._id;
               }
               // store the photo buffer into mongo
               var buf = new Buffer(data);
               gm(data).resize(200,200).toBuffer(function(err, buff){
                  if(err) throw err;
                  doc.avatar.bin = new Buffer(buff).toString('base64');//new Buffer(data).toString('base64');
                  doc.avatar.mime = req.files.myFile.name;
                  doc.save(function(err){
                     if(err) throw err;
                     if(!req.user.userdetail){
                        req.user.userdetail = doc._id;
                        req.user.save(function(err){
                           res.redirect('/users/profile/' + req.user._id);
                        });
                     }else
                        res.redirect('/users/profile/' + req.user._id);
                  });
               });
            });
         });
      });




   // User Edit
   app.route('/users/profile/edit/:id')
      .get(app.isLoggedIn, function(req, res) {
         var id = req.params.id;
         if(req.user && (req.user._id.toString() == id) || (req.user.role && req.user.role=='admin' ) ){
            Domain.User.findById(id).populate('club.club').exec(function(err, doc){
                if(err) throw err;
                res.render('users/profile_edit', {profile: doc, user: req.user, message: req.flash('profilesettingsMessage'), csrf: req.csrfToken() });
            });
         }else  res.redirect('/users/profile/' + id);
      })
      .post(app.isLoggedIn, function(req, res){
         var id = req.params.id;
         if(req.user.role!='admin' && req.user._id.toString() != id) res.send(404, 'prohibited operation!!');

         var upd        = {};
         upd.firstname  = req.body.firstname;
         upd.lastname   = req.body.lastname;
         if(req.user.role == 'admin')
            upd.role    = req.body.role

         Domain.User.update({_id: ObjectID(id)},upd, function(err, num){
            if(err) throw err;
            res.redirect('/users/profile/' + id);
         });
      });




};




